#!/usr/bin/env python3
# $Id: genmac3.py fc65281b178f 2012/12/22 08:44:41 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: fc65281b178f $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-12-22 08:44:41Z $"

# Python imports
import hashlib
import optparse
import sys

from venya3.lib import cmdparser, exception, stdlib

sha256 = lambda string: hashlib.sha256(string.encode("ascii")).hexdigest()

class getmac(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-l", "--length", action ="store",
            help = "Length of the MAC address, options: 48 or 64",
            type = "choice", choices = ["48", "64"], default = 48,
            dest = "length"),
         ) + cmdparser.GetOpt.option_list

   help = """
   Generate random mac address either of length 48 or 64
   """

   def __init__(self, **Keywords):
      super(self.__class__, self).__init__(**Keywords)

   def handle(self):
      (options, args) = self.parse()

      length = 0
      if options.length:
         try:
            length = int(options.length)
         except ValueError as err:
            self.error(err.message)

      value = 0
      if (length == 48):
         value = 11
      elif (length == 64):
         value = 15

      tempstr = stdlib.GetRandomString(100)
      mac = "0"
      if value:
         for ch in sha256(tempstr)[:value]:
            length = len(mac) + 1
            if (length % 3) == 0:
               mac += ":"

            mac += ch

      print(mac)

if __name__ == "__main__":
   genmac = None
   try:
      genmac = getmac(version = 1.0, args = sys.argv)
      if len(genmac) <= 1:
         genmac.printhelp()
      else:
         genmac.handle()
   except exception.GetOptError as err:
      print(err.message)
      sys.exit(1)
